import 'dart:convert';
import 'dart:developer';

import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shimo_app/pages/components/confirmdDialog.dart';
import 'package:shimo_app/pages/components/hint.dart';
import 'package:shimo_app/services/db_service.dart';

import '../../services/device_service.dart';
import '../../utils/utils.dart';
import 'state.dart';

class SettingComponentController extends GetxController {
  final Setting_componentState state = Setting_componentState();
  final dbService = Get.find<DbService>();
  final deviceService = Get.find<DeviceService>();
  final List<User> userList = [];
  final List<User> _lUsers = [];
  final Map<String, dynamic> addUserInfo = {};
  Map<String, dynamic> editUserInfo = {};
  Map<UserPrivilege, String> privilegeMap = {
    UserPrivilege.userTop: "顶级",
    UserPrivilege.userSuperAdmin: "超级管理员",
    UserPrivilege.userAdmin: "管理员",
    UserPrivilege.userExecutor: "操作员",
  };
  int currentTab = 0;
  int inputKp11 = 0;
  int inputKi11 = 0;
  int inputKd11 = 0;
  int inputKp12 = 0;
  int inputKi12 = 0;
  int inputKd12 = 0;
  int inputKp13 = 0;
  int inputKi13 = 0;
  int inputKd13 = 0;

  int inputKp21 = 0;
  int inputKi21 = 0;
  int inputKd21 = 0;
  int inputKp22 = 0;
  int inputKi22 = 0;
  int inputKd22 = 0;
  int inputKp23 = 0;
  int inputKi23 = 0;
  int inputKd23 = 0;

  int Kp11 = 0;
  int Ki11 = 0;
  int Kd11 = 0;
  int Kp12 = 0;
  int Ki12 = 0;
  int Kd12 = 0;
  int Kp13 = 0;
  int Ki13 = 0;
  int Kd13 = 0;

  int Kp21 = 0;
  int Ki21 = 0;
  int Kd21 = 0;
  int Kp22 = 0;
  int Ki22 = 0;
  int Kd22 = 0;
  int Kp23 = 0;
  int Ki23 = 0;
  int Kd23 = 0;
  String _logPath = "";
  String _funcPath = "";
  String appVersion = "";

  @override
  void onInit() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    // String appName = packageInfo.appName;
    // String packageName = packageInfo.packageName;
    Kp11 = deviceService.getCalibrationValue("Kp11");
    Ki11 = deviceService.getCalibrationValue("Ki11");
    Kd11 = deviceService.getCalibrationValue("Kd11");
    Kp12 = deviceService.getCalibrationValue("Kp12");
    Ki12 = deviceService.getCalibrationValue("Ki12");
    Kd12 = deviceService.getCalibrationValue("Kd12");
    Kp13 = deviceService.getCalibrationValue("Kp13");
    Ki13 = deviceService.getCalibrationValue("Ki13");
    Kd13 = deviceService.getCalibrationValue("Kd13");
    Kp21 = deviceService.getCalibrationValue("Kp21");
    Ki21 = deviceService.getCalibrationValue("Ki21");
    Kd21 = deviceService.getCalibrationValue("Kd21");
    Kp22 = deviceService.getCalibrationValue("Kp22");
    Ki22 = deviceService.getCalibrationValue("Ki22");
    Kd22 = deviceService.getCalibrationValue("Kd22");
    Kp23 = deviceService.getCalibrationValue("Kp23");
    Ki23 = deviceService.getCalibrationValue("Ki23");
    Kd23 = deviceService.getCalibrationValue("Kd23");
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    appVersion = "$version+$buildNumber";
    // print('App Version: $version');
    // print('Build Number: $buildNumber');
    refreshUserList();
    _logPath = deviceService.logPath ?? "";
    _funcPath = deviceService.funcPath ?? "";
    super.onInit();
  }

  String get logPath {
    return _logPath;
  }

  set logPath(String path) {
    if (path == _logPath) return;
    _logPath = path;
    deviceService.logPath = path;
    dbService.setValue("logPath", path);
  }

  String get funcPath {
    return _funcPath;
  }

  set funcPath(String path) {
    if (path == _funcPath) return;
    _funcPath = path;
    deviceService.funcPath = path;
    dbService.setValue("funcPath", path);
  }

  void refreshUserList() {
    final raw = dbService.getValue<String>("users");
    userList.clear();
    _lUsers.clear();
    if (raw != null && raw.length > 2) {
      final j = jsonDecode(raw);
      print("users:$j");
      for (var i in j) {
        final user = User(
            i['name'],
            i['id'],
            UserPrivilege.values[i['privilege']],
            i['password'],
            i['createdAt'],
            i["enable"],
            i["createdBy"]);
        _lUsers.add(user);
        if (deviceService.currentUser != null &&
            deviceService.currentUser!.privilege.index <= i['privilege']) {
          continue;
        }
        userList.add(user);
      }
    }
    update();
  }

  Future<bool> setAccDuration11(int val) async {
    final result = await deviceService.saveCalibrationValue("Ki11", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Ki11 = val;
    return true;
  }

  Future<bool> setTargetTemperature11(int val) async {
    final result = await deviceService.saveCalibrationValue("Kp11", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kp11 = val;
    return true;
  }

  Future<bool> setBalanceDuration11(int val) async {
    final result = await deviceService.saveCalibrationValue("Kd11", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kd11 = val;
    return true;
  }

  Future<bool> setAccDuration12(int val) async {
    final result = await deviceService.saveCalibrationValue("Ki12", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Ki12 = val;
    return true;
  }

  Future<bool> setTargetTemperature12(int val) async {
    final result = await deviceService.saveCalibrationValue("Kp12", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kp12 = val;
    return true;
  }

  Future<bool> setBalanceDuration12(int val) async {
    final result = await deviceService.saveCalibrationValue("Kd12", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kd12 = val;
    return true;
  }

  Future<bool> setAccDuration13(int val) async {
    final result = await deviceService.saveCalibrationValue("Ki13", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Ki13 = val;
    return true;
  }

  Future<bool> setTargetTemperature13(int val) async {
    final result = await deviceService.saveCalibrationValue("Kp13", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kp13 = val;
    return true;
  }

  Future<bool> setBalanceDuration13(int val) async {
    final result = await deviceService.saveCalibrationValue("Kd13", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kd13 = val;
    return true;
  }

  Future<bool> setAccDuration21(int val) async {
    final result = await deviceService.saveCalibrationValue("Ki21", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Ki21 = val;
    return true;
  }

  Future<bool> setTargetTemperature21(int val) async {
    final result = await deviceService.saveCalibrationValue("Kp21", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kp21 = val;
    return true;
  }

  Future<bool> setBalanceDuration21(int val) async {
    final result = await deviceService.saveCalibrationValue("Kd21", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kd21 = val;
    return true;
  }

  Future<bool> setAccDuration22(int val) async {
    final result = await deviceService.saveCalibrationValue("Ki22", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Ki22 = val;
    return true;
  }

  Future<bool> setTargetTemperature22(int val) async {
    final result = await deviceService.saveCalibrationValue("Kp22", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kp22 = val;
    return true;
  }

  Future<bool> setBalanceDuration22(int val) async {
    final result = await deviceService.saveCalibrationValue("Kd22", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kd22 = val;
    return true;
  }

  Future<bool> setAccDuration23(int val) async {
    final result = await deviceService.saveCalibrationValue("Ki23", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Ki23 = val;
    return true;
  }

  Future<bool> setTargetTemperature23(int val) async {
    final result = await deviceService.saveCalibrationValue("Kp23", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kp23 = val;
    return true;
  }

  Future<bool> setBalanceDuration23(int val) async {
    final result = await deviceService.saveCalibrationValue("Kd23", val);
    showHint("设置${result ? "成功" : "失败"}",
        result ? HintType.SUCCESS : HintType.DANGER);
    if (!result) {
      return false;
    }
    Kd23 = val;
    return true;
  }

  void delUser(String id, String name) async {
    // if (!await showConfirmDialog("确认删除用户${name}?")) {
    //   return;
    // }
    _lUsers.removeWhere((element) => element.id == id);
    userList.removeWhere((element) => element.id == id);
    _setUserToLocal();
    update();
    showHint("删除成功", HintType.SUCCESS);
  }

  bool saveUser(Map<String, dynamic> info) {
    final e = _lUsers.firstWhereOrNull(
        (element) => element.name == info["name"] || element.id == info['id']);
    if (e != null) {
      showHint("名称或账户重复", HintType.DANGER);
      return false;
    }

    // 将 int 转换为 UserPrivilege 枚举
    UserPrivilege privilege;
    if (info['privilege'] is UserPrivilege) {
      privilege = info['privilege'] as UserPrivilege;
    } else if (info['privilege'] is int) {
      final index = info['privilege'] as int;
      if (index >= 0 && index < UserPrivilege.values.length) {
        privilege = UserPrivilege.values[index];
      } else {
        showHint("权限值无效", HintType.DANGER);
        return false;
      }
    } else {
      showHint("权限类型错误", HintType.DANGER);
      return false;
    }

    final user = User(
      info['name'],
      info['id'],
      privilege, // 使用转换后的枚举值
      // info['privilege'],
      info['password'],
      Utils.getCurrentTimeStamp(),
      true,
      deviceService.currentUser == null ? "" : deviceService.currentUser!.id,
    );
    userList.add(user);
    _lUsers.add(user);
    _setUserToLocal();
    update();
    showHint("新增成功", HintType.SUCCESS);
    return true;
  }

  void _setUserToLocal() {
    List<Map<String, dynamic>> m = [];
    for (var i in _lUsers) {
      m.add(i.toJson());
    }
    dbService.setValue("users", jsonEncode(m));
  }
}
